package com.sinosoft.sinopay.apiservise.chinapay.service;

import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sinosoft.sinocloud.platform.base.SinoBaseCheckException;
import com.sinosoft.sinocloud.platform.base.SinoBaseService;
import com.sinosoft.sinocloud.platform.common.util.DateUtil;
import com.sinosoft.sinopay.api.common.config.ENUM_PAY_BIZ_REPORTLOG_STATE;
import com.sinosoft.sinopay.api.common.config.ENUM_PAY_REQUEST_TYPE;
import com.sinosoft.sinopay.api.common.config.ENUM_PAY_RESPONSE_RESULT;
import com.sinosoft.sinopay.api.common.dto.pay.PayInfoReturnDTO;
import com.sinosoft.sinopay.api.pay.dto.InterPayRequestInfo;
import com.sinosoft.sinopay.api.pay.service.InterPayApiService;
import com.sinosoft.sinopay.apiservise.chinapay.dto.ChinaPayParaDto;
import com.sinosoft.sinopay.apiservise.chinapay.util.ChinaPayAnayResUtil;
import com.sinosoft.sinopay.apiservise.chinapay.util.ChinapayConfig;
import com.sinosoft.sinopay.apiservise.chinapay.util.PaymentUtil;

/** 
 * 【上银联接口支付API实现】
 * @Description: 上银联接口支付API实现
 * @author liuyjsh@sinosoft.com.cn
 * @date 2016年5月24日 下午7:00:35 
 * @version V1.0
 */
@Service("interPayApiService72")
public class ChinaPayApiServiceImpl extends SinoBaseService implements InterPayApiService {
    @Autowired
    private LogReportThirdFacadeService logReportThirdFacadeService;

    /** 
     * 请求上银联支付，不对参数进行校验。校验过程请在调用层处理
     */
    public PayInfoReturnDTO payRequest(InterPayRequestInfo interPayRequestInfo) throws SinoBaseCheckException, DealException, Exception {
        //封装返回参数
        PayInfoReturnDTO payInfoReturn = new PayInfoReturnDTO();
        //请求第三方支付日志
        PayMonitorThirdpayReportLog payMonitorThirdpayReportLog = new PayMonitorThirdpayReportLog();

        try {
            //1、获取上银联支付参数
            String orderNo = interPayRequestInfo.getPayNo();//支付号码
            String openBankId = interPayRequestInfo.getOpenBank();//开户行编码
            String cardType = "0";//卡折标记  0:卡,1:折 
            String cardNo = interPayRequestInfo.getAccountNo();//银行账号，卡号
            String usrName = interPayRequestInfo.getAccountName(); //持卡人姓名
            String certType = interPayRequestInfo.getCardType();//证件类型      
            String curyId = interPayRequestInfo.getCardNo();//证件号
            String transAmt = interPayRequestInfo.getPayAmount();//金额
            String purpose = "支付";//用途说明，原样返回，不参与数据签名。可为空
            String priv1 = interPayRequestInfo.getPriv1();//私有域
            String transDate = DateUtil.getCurrentDate("yyyyMMdd");//当前时间

            //2、封装请求参数（以做签名处理）
            ChinaPayParaDto chinaPayParaDto = new ChinaPayParaDto(transDate, orderNo, openBankId, cardType, cardNo, usrName, certType, curyId,
                    transAmt, purpose, priv1);
            logger.info("签名参数-->" + chinaPayParaDto.getToSignValues());
            logger.info("签名后值-->" + chinaPayParaDto.getChkValue());

            String url = ChinapayConfig.getPayUrl();
            //请求参数
            String requestPara = chinaPayParaDto.getRequestPara();

            //记录请求第三方支付日志文件
            payMonitorThirdpayReportLog.setRequestDate(new Date());//请求时间
            payMonitorThirdpayReportLog.setRequestContent(requestPara);//请求报文
            payMonitorThirdpayReportLog.setRequestType(ENUM_PAY_REQUEST_TYPE.SEND.code());//请求类型 :接收 、发送
            payMonitorThirdpayReportLog.setPayNo(interPayRequestInfo.getPayNo());//支付号码
            payMonitorThirdpayReportLog.setThirdpayCode(interPayRequestInfo.getThirdpayCode());//第三方支付渠道编码
            payMonitorThirdpayReportLog.setMerchantCode(interPayRequestInfo.getMerchantCode());//商户编码
            payMonitorThirdpayReportLog.setRequestUrl(url);//请求URL地址

            //调用上银联接口，进行支付
            String result = PaymentUtil.postData(url, requestPara);

            payMonitorThirdpayReportLog.setResponseContent(result);//返回报文
            logger.info("上银联代支付返回信息-->" + result);

            //解析上银联应答信息，00表示成功
            String responseCode = ChinaPayAnayResUtil.getResponseCode(result);
            //把返回结果转换为map
            Map<String, String> map = PaymentUtil.analyRespose(result);

            String transStat = map.get("transStat");//代扣状态
            String sign = map.get("chkValue");//签名
            String payAmount = map.get("transAmt");
            String payNo = map.get("orderNo");

            //把map转换为object对象            
            if ("00".equals(responseCode)) {
                payMonitorThirdpayReportLog.setStatus(ENUM_PAY_BIZ_REPORTLOG_STATE.PAY_SUCC.code());//状态
                payInfoReturn.setReturnCode("000000");
                payInfoReturn.setReturnMsg(ENUM_PAY_BIZ_REPORTLOG_STATE.PAY_SUCC.desc());
                payInfoReturn.setPayType(interPayRequestInfo.getPayType());
//                payInfoReturn.setMerchantCode(interPayRequestInfo.getMerchantCode());//商户编码
                payInfoReturn.setBizNo(interPayRequestInfo.getBizNo());
                payInfoReturn.setSign(sign);
//                if ("1001".equals(transStat)) {
//                    payInfoReturn.setTransStat(ENUM_PAY_RESPONSE_RESULT.SUCCESS.code());
//                } else {
//                    payInfoReturn.setTransStat(ENUM_PAY_RESPONSE_RESULT.FAIL.code());
//                }
                payInfoReturn.setPayNo(payNo);
                payInfoReturn.setPayAmount(payAmount);

            } else {
                payMonitorThirdpayReportLog.setStatus(ENUM_PAY_BIZ_REPORTLOG_STATE.PAY_FAIL.code());
//                payInfoReturn.setTransStat(ENUM_PAY_RESPONSE_RESULT.FAIL.code());
                //错误信息描述
                String errorMess = PaymentUtil.unicodeToGB((String) map.get("message"));
                String str = URLDecoder.decode(result, "UTF-8");

                payInfoReturn.setReturnCode("111111");
                payInfoReturn.setReturnMsg(errorMess);
                payMonitorThirdpayReportLog.setResponseContent(str);//上银联返回报文
                logger.error("错误描述-->" + errorMess + "-->错误信息" + str);
            }

        } catch (DealException de) {
            logger.error("请求第三方支付渠道失败：" + de);
            payMonitorThirdpayReportLog.setStatus(ENUM_PAY_RESPONSE_RESULT.EXCEPTION.code());//应答失败       	
        } catch (Exception e) {
            payMonitorThirdpayReportLog.setStatus(ENUM_PAY_RESPONSE_RESULT.EXCEPTION.code());//应答失败
            throw new Exception(e.getMessage());
        } finally {
            //记录与第三方支付之间支付请求日志
            logReportThirdFacadeService.thirdPayLogReport(payMonitorThirdpayReportLog);
        }

        return payInfoReturn;
    }

}
